#include "familymodel.h"
#include <QDebug>

FamilyModel::FamilyModel(QObject *parent) :
    QAbstractTableModel(parent)
{
}


void FamilyModel::load_data(QVariant qv_ten_index)
{
    if(!qv_ten_index.isValid()) return;
    mqvl_indexes.clear();
    mqhl_data.clear();
    mqv_ten_index = qv_ten_index;
    mqvl_indexes = mp_dbms->get_db(LAKDB_FAMILIES)->findDataEq(FLD_FAM_TINDEX,mqv_ten_index,&mqhl_data);
    qDebug()<<"Family Model. data loaded. size:"<<mqvl_indexes.size();
}

int FamilyModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return mqvl_indexes.size();
}

int FamilyModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 3;
}

QVariant FamilyModel::data(const QModelIndex &index, int role) const
{
    if(role!= Qt::DisplayRole) return QVariant();
    int r = index.row();
    int c = index.column();
    QString qstr;
    switch(c)
    {
    case 0: qstr =  mp_dbms->get_fam_member_fio(mqhl_data.at(r)); break;
    case 1: qstr = mqhl_data.at(r).value(FLD_FAM_DOB).toDate().toString("dd.MM.yy"); break;
    case 2: qstr = mqhl_data.at(r).value(FLD_FAM_RELATION).toString(); break;
    }
    return QVariant(qstr);
}

QVariant FamilyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role != Qt::DisplayRole) return QVariant();
    if(orientation == Qt::Vertical) return QVariant();
    QString qstr;
    switch(section)
    {
    case 0: qstr = RUSTR("Фамилия И.О."); break;
    case 1: qstr = RUSTR("Дата рожд."); break;
    case 2: qstr = RUSTR("Степень родства"); break;
    }
    return QVariant (qstr);
}

QVariant FamilyModel::get_db_index(const QModelIndex &index)
{
    if(!index.isValid()) return QVariant();
    return mqvl_indexes.at(index.row());
}

QModelIndex FamilyModel::get_model_index(const QVariant &qv_index)
{
    if(!qv_index.isValid()) return QModelIndex();
    int r = mqvl_indexes.indexOf(qv_index);
    if(r < 0) return QModelIndex();
    return createIndex(r,0);
}

SLEE_HDB_REC FamilyModel::get_data(const QVariant &qv_index)
{
    int r = mqvl_indexes.indexOf(qv_index);
    if(r <0) return SLEE_HDB_REC();
    return mqhl_data.at(r);
}

void FamilyModel::update_data(const QVariant &qv_index)
{
    int r = mqvl_indexes.indexOf(qv_index);
    if(r < 0) return;
    mqhl_data[r] = mp_dbms->get_data(LAKDB_FAMILIES,qv_index);
}
